// to be continued...
DateUitl={
    formater:{"yyyy-mm-dd":{val:"yyyy-mm-dd",separator:"-"}},
    toDate:function(dateString,formater){
        if(!dateString||!formater){
            alert("Lack of necessary parameters (dateString,formater)");
            return false;
        }
        if(this.formater.hasOwnProperty(formater)){
            var f = this.formater[formater];
            var arr = dateString.split(f.separator);
            return new Date(arr[0],arr[1],arr[2]);
        }
    },
    toDateString:function(date,formater){
        if(!date||!formater){
            alert("Lack of necessary parameters (dateString,formater)");
            return false;
        }
        if(this.formater.hasOwnProperty(formater)){
            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); 
        }
    }
};
var QS_Forex_CRT = function(config,FI,callback){
    this.config=$.extend(true,{dragAble:false,exchangeId:"245",autoHeight:false,forexList:[],decimal:5},config);
    this.container=this.config.container;
    this.el = null;
	this.callbacks = $.extend(true,{onCellDoubleClick:function(){}},callback);
    this.HTML="<div class='forex-crt'></div>";
    this.exchangeId=this.config.exchangeId;
    this.forexs=["USD","EUR","JPY","GBP","CHF","AUD","CAD","HKD","NZD","CNY","ZAR","DKK","TWD"];
	if(config&&config.forexList){
		this.forexs=config.forexList;;
	}
    this.dataGridPositionMap = {};
    this.forexsSubscribeList=[];
    this.needFlushAllForexsCheckboxs=false;
    this.lastestMouseoverCell=null;
    this.grid = null;
    this.tipTimeout = null;
    this.isHistorical = false;
	this.isRowDrag = false;
    this.FI=$.extend(this.getInterface(),FI);
};
QS_Forex_CRT.prototype={
	getInterface:function(){
        return {
            push: {
                subscribeSymbols: function(){
                },
                unSubscribe: function(){
                },
                parseCfg: function(){
                },
                setTickerValidation: function(){
                },
                updateDataFromGData: function(){
                },
                getCfg: function(){
                },
                updateData: function(){
                },
				getSubscribeKey :function(){
					
				},
				callback :function(){}
            },
            history: {
                getSubscribeKey: function(){
                },
                updateHistoricalData: function(){
                },
                getCfg: function(){
                }
            },
            tip: {
                hide: function(){
                },
                show: function(){
                }
                
            },
            settingPanel: {
                onOpenSettingPN: function(){
                },
                initCheckBoxs: function(){
                },
                getDom: function(){
                },
				parseCfg:function(){
					
				}
            }
        }
	},
	getMinWidth:function(){
		return this.forexs.length*25;
	},
    _init:function(){
        this._crossForexsMapping();
        if(!this.isHistorical){
            this.FI.push.subscribeSymbols(this.forexsSubscribeList);
        }
        var fs = this.forexs, dataMap = {}, dataList = [];
        for (var i = 0; i < fs.length; i++) {
            dataMap = {
                "rowid": fs[i]
            };
            for (var j = 0; j < fs.length; j++) {
                dataMap[fs[j]] = "-";
            }
            dataList.push(dataMap);
        }
        var self =this;
        if (this.grid == null) {
            this.grid = new Util.DataGrid(this.el, {}, {
                column: this._getColumnList(),
                indexColKey: 'Key',
                rowLayout: 'grid',
                cellResize: false,
                sortable: false,
                cellRearrange: true,
				//showXScrollbar: true,
				
                showYScrollbar: true,
                autoWidth: false,
                rowSelectable:false,
                rowDragable: this.config.dragAble,
                rowDropable: true,
                rowDragDropGroup: 'gridDDGroup',
                autoHeight: this.config.autoHeight
            }, {
                onCellMouseover: function(e, cell, row){
                    var y = cell.key;
                    var x = row.id;
                    var key = self._getKey(x,y);
                    self.lastestMouseoverCell=key;
                    if(!gData[key]){
                        self._hideTip();
                        return;
                    }
                    var data = gData[key];
                    if(self.tipTimeout!=null){
                        clearTimeout(self.tipTimeout);
                    }
                    self.tipTimeout = setTimeout(function(){
                        self._showTip(data,cell,x,y);
                    },500);
                    self.grid.header.row.cells[cell.key].el.addClass('rtq-grid-cell-highlight');
                    row.cells["rowid"].el.addClass('rtq-grid-cell-highlight');
                },
                onCellMouseout: function(e, cell, row){
                    if(self.tipTimeout!=null){
                        clearTimeout(self.tipTimeout);
                    }
                    self._hideTip();
                    self.grid.header.row.cells[cell.key].el.removeClass('rtq-grid-cell-highlight');
                    row.cells["rowid"].el.removeClass('rtq-grid-cell-highlight');
                },
                onRowDragStart: function(e, proxy, row){
					if(!self.config.dragAble){
						return;
					}
                    if(!gData[self.lastestMouseoverCell]){
						proxy._ticker = null;
						proxy._originWigetType=self.__winObj.widget.type;
						//proxy._stopEvent=true;
						//row.dragObj.stop();
                        return;
                    }
                    proxy._cpnId = self.id;
                    proxy._ticker = self.lastestMouseoverCell;
                    proxy._secType = gData[self.lastestMouseoverCell].type;
					self.isRowDrag = true;
                    proxy.html(gData[self.lastestMouseoverCell].exch + ':' + gData[self.lastestMouseoverCell].ticker);
                },
                onCellRearrange: function(){
                    var list = self.grid.getColumnCfg();
                    var tempList = [];
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].header != "") {
                            tempList.push(list[i].header);
                        }
                    }
                    self._resetColumns(tempList);
                },

				onCellClick:function(e, cell,row){
					var y = cell.key;
                    var x = row.id;
                    var key = self._getKey(x,y);
					if(self.callbacks&&typeof(self.callbacks.onCellClick)=="function"){
						self.callbacks.onCellClick(key);
					}
				},
                onRowRearrange: function(){
                    self._resetColumns(self.grid.getIDs());
                }
            });
        } else {
            this.grid.setColumnCfg(this._getColumnList());
        }
        this.grid.reBindData(dataList);
		
        this._applyCallback();
        this._updateDataOnLoad();
        this.changeOutSize();
        
    },
    _hideTip:function(){
        this.FI.tip.hide();
    },
    _applyCallback:function(){
        var self = this;
        this.FI.push.callback.updateData = function(gKey, v, chg){
			if(self.isHistorical){
				return;
			}
            self._updateData(gKey, v, chg);
        }
        if (this.FI.history.callback) {
            this.FI.history.callback.updateData = function(gKey, v, chg){
                self._updateData(gKey, v, chg);
            }
        }
        
        if (this.FI.settingPanel.callback ) {
            this.FI.settingPanel.callback.changeForexs = function(list){
                self._clearForexBoard();
                self.forexs = list;
                self._init();
            }
        }
        if (this.FI.settingPanel.callback ) {
            this.FI.settingPanel.callback.changeMonitor = function(v){
                // self.FI.push.monitor = v;
                self.FI.push.parseCfg({
                    monitor: v
                });
                self._init();
            }
        }
        if (this.FI.settingPanel.callback) {
            this.FI.settingPanel.callback.changeRate = function(v){
                self.FI.push.parseCfg({
                    rate: v
                });
                //self.FI.push.rate = v;
                self._init();
            }
        }
        if (this.FI.settingPanel.callback) {
            this.FI.settingPanel.callback.changeDate = function(v){
                self.isHistorical = true;
				self._init();
                self._multiThreadGetHistoricalData(v);
            }
        }
    },
    _showTip:function(data,cell,x,y){
        var self = this;
		if(!cell.el){
			return;
		}
        var pos = cell.el.offset();
        var left = pos.left + cell.el.width() + 10;
        if ((220 + cell.el.offset().left + cell.el.width()) > $(window).width()) {
            left = pos.left - 210;
        }
        this.FI.tip.show({x:left,y:pos.top-30},{Ticker:x + "/" + y,BidPrice:self._tipNumberFormat(data.BidPrice),AskPrice:self._tipNumberFormat(data.AskPrice),OpenPrice:self._tipNumberFormat(data.OpenPrice),HighPrice:self._tipNumberFormat(data.HighPrice),ClosePrice:self._tipNumberFormat(data.ClosePrice),LowPrice:self._tipNumberFormat(data.LowPrice),Chg:self._tipNumberFormat(data.Chg),"Chg%":self._tipNumberFormat(data["Chg%"]) + "%",Date:data.Date});
    },
    _tipNumberFormat:function(v){
        if(!v){
            return "-";
        }
        return this._formatNumber(v.toFixed(this.config.decimal));
    },
    _resetColumns:function(list){
        this.forexs = list;
        this._init();
    },
    _getColumnList:function(){
       var per = 88/(this.forexs.length)+"%";
	   
		//var per ='55px';
        var headerList = [];
            headerList.push({
                header: "",
                dataIndex: 'rowid',
                width: "8%",
                height: 0,
                dataType: 'string',
                className: '',
				renderer:function(v){
					return '<div class="qs-cell-'+v+'">'+v+'</div>';
				}
            });
            for (var i = 0; i < this.forexs.length; i++) {
                headerList.push({
                    header: this.forexs[i],
                    dataIndex: this.forexs[i],
                    width: per,
                    height: 0,
                    dataType: 'string',
                    className: 'qs-cell-'+this.forexs[i]
                });
            }
            return headerList;
    },
    getSettingPanelDOM:function(){
		return this.FI.settingPanel.getDom();
    },
    init:function(containerId, cfg,id){
        var self =this;
        this.id = id;
        if (cfg){
            if (cfg.forexs) {
                this.forexs = cfg.forexs.split(",");
            }
            this.FI.push.parseCfg(cfg);
            if(cfg.isHistorical){
                this.isHistorical = cfg.isHistorical;
            }
			
        }
        this.container = $("#"+containerId);
        this.config = $.extend(true,this.config,cfg);
        this.el=$(this.HTML).appendTo(this.container);
        this.FI.settingPanel.parseCfg({checkedList:this.forexs,monitor:this.FI.push.monitor});
        this._init();
    },
    _getCurrentDateAndYesterday:function(date){
        var ed = RTQ_ChartUtil.formatDate(date);
        var st = date;
        st.setDate(st.getDate() - 1);
        return [RTQ_ChartUtil.formatDate(st),ed];
    },
    _getHistoricalSymbols:function(){
        var temp = [];
        for(var i =0;i<this.forexsSubscribeList.length;i++){
            temp.push(this.forexsSubscribeList[i].substr(4,6));
        }
        return temp;
    },
     _updateData:function(gKey,v,chg){
        var map = this.dataGridPositionMap[gKey];
        if(map&&v){
            this.grid.DOMMap[map.x][map.y].innerHTML=this._formatNumber(parseFloat(v).toFixed(this.config.decimal));
            var cellDOM = this.grid.DOMMap[map.x][map.y];
            cellDOM.className=cellDOM.className.replace(/rtq-grid-cell-\w+/g, "");
            cellDOM.className='rtq-grid-cell-ctn'+this._getChangeLevel(chg);
        }
     },
     _formatNumber:function(n){
        return n.toString().substr(0,7);
     },
     _updateDataOnLoad:function(){
        var self =this;
        if(this.isHistorical){
            this._multiThreadGetHistoricalData(new Date());
           
        }else{
            for (var i in gData) {
                this.FI.push.updateDataFromGData(i,gData[i]);
            }
        }
     },
     _multiThreadGetHistoricalData:function(date){
         var datearr = this._getCurrentDateAndYesterday(date);
         var diff = 10;
         for (var i = 0, j = 0; i < this.forexsSubscribeList.length; i += diff, j++) {
             this.FI.history.updateHistoricalData(j, datearr[0], datearr[1], this.forexsSubscribeList.slice(i, i + diff).join(","));
         }
     },
     _getChangeLevel:function(chg){
        if(!chg)return "";
		var n = "";//,r = chg/0.0001;
		if(typeof this.config.customUpDownCls=='function'){
			n=this.config.customUpDownCls(chg);
		}else{
			if(chg<-2.5){
				n ="r1";
			}else if(chg<-0.5){
				n="r2";
			}else if(chg<-0.05){
				n="r3";
			}else if(chg<0.05){
				n="";
			}else if(chg<0.5){
				n="g3";
			}else if(chg<2.5){
				n="g2";
			}else{
				n="g1";
			}
		}
		return n==""?"":" rtq-grid-cell-"+n;
     },
    _getKey:function(v1,v2){
        return this.exchangeId+":"+v1+v2+"FLIT";
    },
    _clearForexBoard:function(){
        this.FI.push.unSubscribe(this.forexsSubscribeList, true);
        this.forexsSubscribeList=[];
        this.dataGridPositionMap={};
    },
    _crossForexsMapping:function(){
        var fs = this.forexs,temp=[],str="",maplist=[];
        for (var i = 0; i < fs.length; i++) {
            for (var j = 0; j < fs.length; j++) {
                if (this.isHistorical) {
                    str =this.FI.history.getSubscribeKey(fs[i],fs[j]);
                } else {
                    str =this.FI.push.getSubscribeKey(fs[i],fs[j]);
                }
                if (i != j) {
                    temp.push(str);
                }
                this.dataGridPositionMap[str] = {
                    x: fs[i],
                    y: fs[j]
                };
            }
        }
        this.forexsSubscribeList = temp;
    },
    changeOutSize:function(w,h){
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height();
        if(this.grid){
			var containerWidth = (this.forexs.length+1)*55+20;
			this.grid.el.find('.rtq-grid-bd').css({'min-width':containerWidth});
            this.grid.resize(w,h);			
			this.grid.el.find('.rtq-grid-hd .rtq-grid-rzrow').css({'width':'100%','min-width':containerWidth});
        }
		if(this.callbacks&&typeof(this.callbacks.onHeightChange)=="function"){
			this.callbacks.onHeightChange();
		}
    },
    acceptTicker:function(t){
		if(!t){
			return;
		}
		t=gIdMap[t];
        if(t.indexOf(":")==3){
            var b = t.substr(4, 6);
            var t1 = b.substr(0, 3), t2 = b.substr(3, 6);
            var flag = false;
            if($.inArray(t1,this.forexs)==-1){
                this.forexs.push(t1);
                flag=true;
            }
            if($.inArray(t2,this.forexs)==-1){
                this.forexs.push(t2);
                flag=true;
            }
            if(flag){
                this._init();
                this.needFlushAllForexsCheckboxs = true;
            }else if(typeof(TEXT)!="undefined"&&typeof(TEXT.ForexExistPair)!="undefined"){
				Util.message(TEXT.ForexExistPair);
			}
			this.isRowDrag = false;
        }
    },
    onOpenSettingPN:function(){
        if(this.needFlushAllForexsCheckboxs){
            this.FI.settingPanel.initCheckBoxs(this.forexs);
            this.needFlushAllForexsCheckboxs = false;
        }
        this.FI.settingPanel.onOpenSettingPN();
    },
    _subscribeSymbols:function(gKeyList){
        if(gKeyList==null||gKeyList.length==0){
            return;
        }
        this.tValidation.checkTickers(gKeyList);
    },
    saveConfig:function(){
        var cfg = {forexs:this.forexs.join(","),isHistorical:this.isHistorical};
        for(var i in this.FI){
            if(typeof(this.FI[i].getCfg)!="function"){
                continue;
            }
            var tempCfg = this.FI[i].getCfg();
            if(!tempCfg){
                continue;
            }
            for(var j in tempCfg){
                cfg[j]=tempCfg[j];
            }
        }
        return cfg;
    }
};


